package com.totoro.tyrank.inventory;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.*;
import com.totoro.tyrank.data.PlayerData;
import com.totoro.tyrank.data.RankingData;
import com.totoro.tyrank.handle.PaginatorHandler;
import com.totoro.tyrank.utils.*;
import io.lumine.xikage.mythicmobs.adapters.bukkit.BukkitItemStack;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 某个排行榜里的内容
 */
public class RankContentInventory {

    /**
     * 存储玩家切换分页数据
     */
    public static Map<UUID, Integer> currentPage = new ConcurrentHashMap<>();

    /**
     * 存储玩家打开的某个排行榜内容标题
     */
    public static Map<UUID, String> currentOpenRankContent = new ConcurrentHashMap<>();

    /**
     * 存储玩家是否正在切换界面，这样就可以在正式关闭时重置当前页
     */
    public static Map<UUID, Boolean> currentChangePageStatus = new ConcurrentHashMap<>();

    /**
     * 打开某个排行榜里内容的箱子GUI
     * @param player 玩家对象
     * @param rankId 排行榜Id
     * @param fromInvRankType InvRankTypeConst
     */
    public static void openMainInv(Player player, String rankId, String fromInvRankType) {
        if(! StrUtil.isNotBlank(fromInvRankType)) {
            fromInvRankType = InvRankTypeConst.ALL_RANK_INV;
        }
        // 获取当前排行榜对象
        Map<String, RankingData> rankDataMap = TyRank.getRankingManager().getRankDataMap();
        if (!StrUtil.isNotBlank(rankId) || ! rankDataMap.containsKey(rankId)) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getInputRankIdError());
            return;
        }
        // 重置分页器
        if(! currentPage.containsKey(player.getUniqueId())) {
            currentPage.put(player.getUniqueId(), 1);
        }
        RankingData rankingData = rankDataMap.get(rankId);

        // 获取当前榜名称和状态
        String rankName = rankingData.getRankName();
        String rankStatus = DateUtil.isCurrentTimeAfter(rankingData.getEndTime()) ?
                TyRank.getLanguageManager().getLanguageData().getGui().getRankItemHasEndedStatus() :
                TyRank.getLanguageManager().getLanguageData().getGui().getRankItemInProgressStatus();
        // 获取GUI名称
        String rankContentInvTitle = TyRank.getLanguageManager().getLanguageData().getGui().getRankContentInvTitle()
                .replaceAll(TagConst.RANK_NAME_TAG, rankName).replaceAll(TagConst.STATUS_TAG, rankStatus);
        currentOpenRankContent.put(player.getUniqueId(), rankContentInvTitle);
        Inventory inv = Bukkit.createInventory(null, 54, rankContentInvTitle);
        ItemStack gridPlateItem = ItemStackUtil.getGridPlateItem();
        // 设置第一排的格挡板
        for (int i = 0; i < 10; i++) {
            inv.setItem(i, gridPlateItem);
        }
        // 设置其他的格挡板
        List<Integer> gridPlateItemOthers = Stream.of(17, 18, 26, 27, 35, 36, 44, 46, 48, 50, 52).collect(Collectors.toList());
        for (Integer gridPlateItemOther : gridPlateItemOthers) {
            inv.setItem(gridPlateItemOther, gridPlateItem);
        }

        // 设置第一排的当前排行榜信息
        ItemStack rankItemStack = ItemStackUtil.getRankItemStackByRankingData(player, rankingData);
        rankItemStack = NBTUtil.addNBT(rankItemStack, NBTKeyConst.VALUE_NAME, rankingData.getValueName());
        rankItemStack = NBTUtil.addNBT(rankItemStack, NBTKeyConst.END_TIME, DateUtil.dateFormatStr(rankingData.getEndTime()));
        rankItemStack = NBTUtil.addNBT(rankItemStack, NBTKeyConst.REFRESH_DATE, DateUtil.formatSeconds(rankingData.getUpdateInterval()));
        rankItemStack = NBTUtil.addNBT(rankItemStack, NBTKeyConst.REMAINING_DATE, DateUtil.getTimeDifference(DateUtil.dateFormatStr(rankingData.getEndTime())));
        // 获取当前打开UI玩家在本次排行榜中的排名
        PlayerData currentPlayerData = TyRank.getPlayerDataManager().getPlayerDataByRankId(player, rankId);
        if(null != currentPlayerData && (null != currentPlayerData.getRanking() && currentPlayerData.getRanking() != - 1)) {
            rankItemStack = NBTUtil.addNBT(rankItemStack, NBTKeyConst.CURRENT_RANKING, "TOP." + currentPlayerData.getRanking());
        } else {
            rankItemStack = NBTUtil.addNBT(rankItemStack, NBTKeyConst.CURRENT_RANKING, "未上榜");
        }
        inv.setItem(4, rankItemStack);

        // 设置这个排行榜里的所有玩家Item
        // 获取该排行榜的当前分页的玩家
        Map<String, PaginatorHandler<PlayerData>> rankPaginatorMap = TyRank.getPlayerDataManager().getRankPaginatorMap();
        // 该行分页的玩家存在才渲染所有玩家Item
            // 所有玩家的slot位置
            // 从10开始 如果变成了：17那么则是19，如果是26，那么则是28，如果是35，那则是37
            PaginatorHandler<PlayerData> playerDataPaginatorHandler = rankPaginatorMap.get(rankId);
            // 获取该分页器的当前页数数据，首先判断当前数据的总页数是否大于当前页数，因为不同排行榜页数或许不一样，如果大于就变成1
            if(currentPage.get(player.getUniqueId()) > playerDataPaginatorHandler.getTotalPages()) {
                currentPage.put(player.getUniqueId(), 1);
            }
            // 正式获取当前分页器的数据
            List<PlayerData> playerDataList = playerDataPaginatorHandler.getPage(currentPage.get(player.getUniqueId()));
            // 玩家头颅物品索引，是从10开始的
            int playerSkullItemIndex = 10;
            for (PlayerData playerData : playerDataList) {
                // 获取玩家头颅
                ItemStack playerDataItem = TyRank.getSkullCacheHandler().getCachedSkull(playerData.getPlayerIdentity());
                // 获取玩家名而不是标识
                String playerName = TyRank.getPlayerDataManager().getPlayerName(playerData.getPlayerIdentity());
                playerDataItem = NBTUtil.addNBT(playerDataItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
                playerDataItem = NBTUtil.addNBT(playerDataItem, NBTKeyConst.RANK_ID, rankId);
                playerDataItem = NBTUtil.addNBT(playerDataItem, NBTKeyConst.PLAYER_NAME, playerName);
                playerDataItem = NBTUtil.addNBT(playerDataItem, NBTKeyConst.RANKING, playerData.getRanking().toString());
                playerDataItem = NBTUtil.addNBT(playerDataItem, NBTKeyConst.CURRENT_VALUE, playerData.getCurrentValue());
                ItemMeta playerDataMeta = playerDataItem.getItemMeta();
                // 设置name,获取当前玩家名次的排行预览对象
                RankingData.RankingReceive rankingReceive = TyRank.getRankingManager().getRankingReceiveByRankIdAndRanking(rankId, playerData.getRanking());
                String playerDataItemName = rankingReceive.getItemDisplay().getName().replace(TagConst.PLAYER_TAG, playerName);
                playerDataMeta.setDisplayName(playerDataItemName);
                // 设置Lore
                List<String> playerDataItemLore = rankingReceive.getItemDisplay().getLore().stream().map(lineLore -> lineLore.replace(TagConst.RANKING_TAG, playerData.getRanking().toString()).replace(TagConst.VALUE_TAG, playerData.getCurrentValue())
                        .replace(TagConst.UPDATE_TIME_TAG, playerData.getUpdateDateTime())).collect(Collectors.toList());
                playerDataMeta.setLore(playerDataItemLore);
                playerDataItem.setItemMeta(playerDataMeta);
                inv.setItem(playerSkullItemIndex, playerDataItem);
                playerSkullItemIndex++;
                if(playerSkullItemIndex == 17) {
                    playerSkullItemIndex = 19;
                }
                if(playerSkullItemIndex == 26) {
                    playerSkullItemIndex = 28;
                }
                if(playerSkullItemIndex == 35) {
                    playerSkullItemIndex = 37;
                }
            }

        // 47 属性
        ItemStack attributeItem = new ItemStack(Material.DIAMOND_CHESTPLATE, 1, (short) 0);
        // 设置属性预览名称和Lore
        ItemMeta attributeItemMeta = attributeItem.getItemMeta();
        attributeItemMeta.setDisplayName(TyRank.getLanguageManager().getLanguageData().getGui().getRankingAttributeReceiveName());
        attributeItemMeta.setLore(TyRank.getLanguageManager().getLanguageData().getGui().getRankingAttributeReceiveLore());
        attributeItemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
        attributeItem.setItemMeta(attributeItemMeta);
        attributeItem = NBTUtil.addNBT(attributeItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        attributeItem = NBTUtil.addNBT(attributeItem, NBTKeyConst.RANK_ID, rankId);
        inv.setItem(47, attributeItem);
        // 49 返回
        ItemStack backItem = new ItemStack(Material.ENDER_PEARL, 1, (short) 0);
        ItemMeta backItemMeta = backItem.getItemMeta();
        backItemMeta.setDisplayName(TyRank.getLanguageManager().getLanguageData().getGui().getBackItemName());
        backItemMeta.setLore(TyRank.getLanguageManager().getLanguageData().getGui().getBackItemLore());
        backItem.setItemMeta(backItemMeta);
        backItem = NBTUtil.addNBT(backItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        backItem = NBTUtil.addNBT(backItem, NBTKeyConst.RANK_ID, rankId);
        inv.setItem(49, backItem);
        // 51 奖励
        ItemStack rewardItem = new ItemStack(Material.CHEST, 1, (short) 0);
        ItemMeta rewardItemMeta = rewardItem.getItemMeta();
        rewardItemMeta.setDisplayName(TyRank.getLanguageManager().getLanguageData().getGui().getRankingRewardReceiveName());
        rewardItemMeta.setLore(TyRank.getLanguageManager().getLanguageData().getGui().getRankingRewardReceiveLore());
        rewardItem.setItemMeta(rewardItemMeta);
        rewardItem = NBTUtil.addNBT(rewardItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        rewardItem = NBTUtil.addNBT(rewardItem, NBTKeyConst.RANK_ID, rankId);
        inv.setItem(51, rewardItem);
        // 上一页45 和下一页53 设置
        ItemStack prePageItem = new ItemStack(Material.FEATHER, currentPage.get(player.getUniqueId()), (short)0);
        ItemMeta prePageItemMeta = prePageItem.getItemMeta();
        prePageItemMeta.setDisplayName(ColorUtil.color("当前页数:" + currentPage.get(player.getUniqueId())));
        prePageItemMeta.setLore(Stream.of(ColorUtil.color("&7左键点击前往上一页"),ColorUtil.color("&f右键点击前往第一页")).collect(Collectors.toList()));
        prePageItem.setItemMeta(prePageItemMeta);
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.RANK_ID, rankId);
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.CURRENT_PAGE, currentPage.get(player.getUniqueId()).toString());
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.TOTAL_PAGE, playerDataPaginatorHandler.getTotalPages().toString());
        inv.setItem(45, prePageItem);

        ItemStack nextPageItem = new ItemStack(Material.FEATHER, currentPage.get(player.getUniqueId()), (short)0);
        ItemMeta nextPageItemMeta = nextPageItem.getItemMeta();
        nextPageItemMeta.setDisplayName(ColorUtil.color("当前页数:" + currentPage.get(player.getUniqueId())));
        nextPageItemMeta.setLore(Stream.of(ColorUtil.color("&7左键点击前往下一页"),ColorUtil.color("&f右键点击前往最后一页")).collect(Collectors.toList()));
        nextPageItem.setItemMeta(nextPageItemMeta);
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.RANK_ID, rankId);
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.CURRENT_PAGE, currentPage.get(player.getUniqueId()).toString());
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.TOTAL_PAGE, playerDataPaginatorHandler.getTotalPages().toString());
        inv.setItem(53, nextPageItem);

        player.openInventory(inv);
    }

    /**
     * 点击切换上一页
     * @param player
     */
    public static void preCurrentPage(Player player, String rankId, String fromInvRankType) {
        Integer page = currentPage.getOrDefault(player.getUniqueId(), 1);
        if(page == 1) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyFirstPage());
        } else if (page < 1) {
            currentPage.put(player.getUniqueId(), 1);
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyFirstPage());
            openMainInv(player, rankId, fromInvRankType);
        } else {
            currentPage.put(player.getUniqueId(), currentPage.get(player.getUniqueId()) - 1);
            openMainInv(player, rankId, fromInvRankType);
        }
    }

    /**
     * 点击切换到第一页
     * @param player
     */
    public static void firstCurrentPage(Player player, String rankId, String fromInvRankType) {
        currentPage.put(player.getUniqueId(), 1);
        player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                TyRank.getLanguageManager().getLanguageData().getMsg().getChangeFirstPage());
        openMainInv(player, rankId, fromInvRankType);
    }

    /**
     * 切换下一页
     * @param player
     */
    public static void nextCurrentPage(Player player, String rankId, String fromInvRankType) {
        Map<String, PaginatorHandler<PlayerData>> rankPaginatorMap = TyRank.getPlayerDataManager().getRankPaginatorMap();
        PaginatorHandler<PlayerData> currentRankPaginatorHandler = rankPaginatorMap.get(rankId);
        // 获取总页数
        int totalPages = currentRankPaginatorHandler.getTotalPages();
        Integer page = currentPage.getOrDefault(player.getUniqueId(), 1);
        if(page == totalPages) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyLastPage());
        } else if (page > totalPages) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyLastPage());
            currentPage.put(player.getUniqueId(), totalPages);
            openMainInv(player, rankId, fromInvRankType);
        } else {
            currentPage.put(player.getUniqueId(), currentPage.get(player.getUniqueId()) + 1);
            openMainInv(player, rankId, fromInvRankType);
        }
    }

    /**
     * 点击切换到最后一页
     * @param player
     */
    public static void lastCurrentPage(Player player, String rankId, String fromInvRankType) {
        Map<String, PaginatorHandler<PlayerData>> rankPaginatorMap = TyRank.getPlayerDataManager().getRankPaginatorMap();
        PaginatorHandler<PlayerData> currentRankPaginatorHandler = rankPaginatorMap.get(rankId);
        // 获取总页数
        int totalPages = currentRankPaginatorHandler.getTotalPages();
        currentPage.put(player.getUniqueId(), totalPages);
        player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                TyRank.getLanguageManager().getLanguageData().getMsg().getChangeLastPage());
        openMainInv(player, rankId, fromInvRankType);
    }
}
